#!/bin/bash

if [[ -z "$1" || -z "$2" ]]; then
	echo Specify the in and out protocol file.
	exit 1;
fi

invalid=no;

{
	if ! grep 'input' $1 || ! grep 'output' $2; then
		invalid=yes;
	fi
} > /dev/null

if [[ "$invalid" == 'yes' ]]; then
	echo Invalid input files.
	exit 2;
fi

tmp_file='/tmp/datanames.tmp'
in_names=`grep '<name>' $1 | sed -r -e 's/<[^<]*>//g' -e 's/\s//g' | tee $tmp_file`
length=`cat $tmp_file | wc -l`
out_names=`grep '<name>' $2 | sed -r -e 's/<[^<]*>//g' -e 's/\s//g' -e '/^1.*$/d'`

# generate the header file
{
	echo '/////////////////////////////'
	echo '// Generated by header-gen.sh'
	echo '/////////////////////////////'
	echo
	echo '#ifndef DATANAME_H'
	echo '#define DATANAME_H'
	echo
	echo '#define NUM_OF_NAMES '$length
	echo
	echo 'extern const char * const out_data_names[NUM_OF_NAMES + 1];'
	echo
	echo '// fg output data names'

	for n in $out_names; do
		a=`echo $n | sed 's/-/_/g'`
		a=${a^^*}
		echo -e "#define FGDATA_$a\t\"$n\""
	done

	echo
	echo '#endif // DATANAME_H'
	echo
} > `dirname $1`/../datanames.h

#generate the source file
{
	echo '/////////////////////////////'
	echo '// Generated by header-gen.sh'
	echo '/////////////////////////////'
	echo
	echo '#include <cstdlib>'
	echo '#include "datanames.h"'
	echo
	echo '// The order of the names in the array is important.'
	echo 'const char * const out_data_names[NUM_OF_NAMES + 1] = {'
	for n in $in_names; do
		echo -e "\t\"$n\","
	done
	echo -e "\tNULL"
	echo '};'
} > `dirname $1`/../datanames.cpp

echo 'File generated!'
exit 0;

